
#include "common.h"
#include "conf.h"
#include "globals.h"

static pthread_mutex_t lock;

void log_init(void) 
{
	assert(conf);
	
	if(!error_logp) {
		if(conf->log.error) {
			error_logp = fopen(conf->log.error, "w");
			assert(error_logp);
			setvbuf(error_logp, NULL,  _IONBF, 0);
		}
	}
	if(!warn_logp) {
		if(conf->log.warn) {
			warn_logp = fopen(conf->log.warn, "w");
			assert(warn_logp);
			setvbuf(warn_logp, NULL,  _IONBF, 0);
		}
	}
	if(!debug_logp) {
		if(conf->log.debug) {
			debug_logp = fopen(conf->log.debug, "w");
			if(debug_logp == NULL) {
				fprintf(stderr, "%s %d: %s\n", __FILE__, __LINE__, strerror(errno));
				abort();
			}
			setvbuf(debug_logp, NULL,  _IONBF, 0);
		}
	}
	pthread_mutex_init(&lock, NULL);
}


void vlog_debug(FILE *file, const char *format,...)
{
	assert(conf);

	if(!file) 
		return;

	char new_format[MAX_BUFFER];
	
	pthread_mutex_lock(&lock);
	va_list  va;
	va_start(va, format);
	
	snprintf(new_format, MAX_BUFFER - 1 ,  "%s", format);

	if(vfprintf(file, new_format, va) < 0)
		fprintf(stderr, "Warning. [%s %d] %s\n", __FILE__, __LINE__, strerror(errno));

	va_end(va);
	pthread_mutex_unlock(&lock);
}
